package com.dms.modules.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.modules.community.dto.CommunityFollowDTO;
import com.dms.modules.community.entity.CommunityFollow;
import com.dms.modules.community.mapper.CommunityFollowMapper;
import com.dms.modules.community.service.CommunityFollowService;
import com.dms.modules.message.dto.MessageDetailDTO;
import com.dms.modules.message.websocket.MessageWebSocket;
import com.dms.modules.user.service.UserCenterService;
import com.dms.modules.user.vo.UserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommunityFollowServiceImpl extends ServiceImpl<CommunityFollowMapper, CommunityFollow> implements CommunityFollowService {

    @Autowired
    private UserCenterService userCenterService;
    
    @Autowired
    private MessageWebSocket messageWebSocket;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean followUser(Long userId, Long followedUserId) {
        try {
            // 检查是否已关注
            if (checkIsFollowed(userId, followedUserId)) {
                return false;
            }
            
            // 创建关注记录
            CommunityFollow follow = new CommunityFollow();
            follow.setUserId(userId);
            follow.setFollowedUserId(followedUserId);
            follow.setCreateTime(LocalDateTime.now());
            boolean success = save(follow);
            
            if (success) {
                // 发送关注通知
                sendFollowNotification(userId, followedUserId);
            }
            
            return success;
        } catch (Exception e) {
            log.error("关注用户失败: userId={}, followedUserId={}, error={}", userId, followedUserId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean unfollowUser(Long userId, Long followedUserId) {
        try {
            LambdaQueryWrapper<CommunityFollow> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CommunityFollow::getUserId, userId)
                   .eq(CommunityFollow::getFollowedUserId, followedUserId);
            return remove(wrapper);
        } catch (Exception e) {
            log.error("取消关注失败: userId={}, followedUserId={}, error={}", userId, followedUserId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public IPage<CommunityFollowDTO> getFollowingList(Long userId, Page<CommunityFollowDTO> page) {
        try {
            // 获取关注列表
            IPage<CommunityFollow> followPage = baseMapper.getFollowingList(new Page<>(page.getCurrent(), page.getSize()), userId);
            
            // 获取被关注用户的信息
            List<Long> followedUserIds = followPage.getRecords().stream()
                    .map(CommunityFollow::getFollowedUserId)
                    .collect(Collectors.toList());
            
            return convertToFollowDTO(followPage, userId, followedUserIds);
        } catch (Exception e) {
            log.error("获取关注列表失败: userId={}, error={}", userId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public IPage<CommunityFollowDTO> getFollowerList(Long userId, Page<CommunityFollowDTO> page) {
        try {
            // 获取粉丝列表
            IPage<CommunityFollow> followPage = baseMapper.getFollowerList(new Page<>(page.getCurrent(), page.getSize()), userId);
            
            // 获取粉丝用户的信息
            List<Long> followerIds = followPage.getRecords().stream()
                    .map(CommunityFollow::getUserId)
                    .collect(Collectors.toList());
            
            return convertToFollowDTO(followPage, userId, followerIds);
        } catch (Exception e) {
            log.error("获取粉丝列表失败: userId={}, error={}", userId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public boolean checkIsFollowed(Long userId, Long followedUserId) {
        LambdaQueryWrapper<CommunityFollow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CommunityFollow::getUserId, userId)
               .eq(CommunityFollow::getFollowedUserId, followedUserId);
        return count(wrapper) > 0;
    }

    /**
     * 转换为FollowDTO
     */
    private IPage<CommunityFollowDTO> convertToFollowDTO(IPage<CommunityFollow> followPage, Long userId, List<Long> targetUserIds) {
        // 获取用户信息
        Map<Long, UserInfoVO> userInfoMap = targetUserIds.stream()
            .map(id -> {
                try {
                    return userCenterService.getUserInfo(id);
                } catch (Exception e) {
                    log.warn("获取用户信息失败: userId={}, error={}", id, e.getMessage());
                    return null;
                }
            })
            .filter(info -> info != null)
            .collect(Collectors.toMap(UserInfoVO::getId, info -> info));
        
        // 转换为DTO
        List<CommunityFollowDTO> records = followPage.getRecords().stream().map(follow -> {
            CommunityFollowDTO dto = new CommunityFollowDTO();
            Long targetUserId = follow.getUserId().equals(userId) ? follow.getFollowedUserId() : follow.getUserId();
            UserInfoVO userInfo = userInfoMap.get(targetUserId);
            
            dto.setUserId(targetUserId);
            if (userInfo != null) {
                dto.setNickname(userInfo.getNickname());
                dto.setAvatar(userInfo.getAvatar());
            } else {
                dto.setNickname("已注销用户");
                dto.setAvatar("/static/images/default-avatar.jpg");
            }
            dto.setBio(""); // 暂时不显示用户简介
            dto.setFollowTime(follow.getCreateTime());
            
            // 检查是否互相关注
            dto.setIsFollowEachOther(baseMapper.checkFollowEachOther(userId, targetUserId) > 0);
            return dto;
        })
        .collect(Collectors.toList());
        
        // 构建返回结果
        IPage<CommunityFollowDTO> result = new Page<>(followPage.getCurrent(), followPage.getSize(), followPage.getTotal());
        result.setRecords(records);
        return result;
    }

    /**
     * 发送关注通知
     */
    private void sendFollowNotification(Long userId, Long followedUserId) {
        try {
            // 获取用户信息
            UserInfoVO userInfo = userCenterService.getUserInfo(userId);
            if (userInfo == null) {
                return;
            }

            // 构建消息
            MessageDetailDTO message = new MessageDetailDTO();
            message.setType(1); // 1-系统通知
            message.setTitle("新增粉丝");
            message.setContent(String.format("%s 关注了你", userInfo.getNickname()));
            message.setUserId(followedUserId);

            // 发送WebSocket消息
            messageWebSocket.sendMessage(followedUserId, message);
        } catch (Exception e) {
            log.error("发送关注通知失败: userId={}, followedUserId={}, error={}", 
                    userId, followedUserId, e.getMessage(), e);
        }
    }
} 